#include "testpage.h"
#include <QPushButton>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>

#include "application.h"
#include "modulemanager.h"
#include "eventid.h"
#include "event.h"

TestPage::TestPage(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle(tr("TestPage"));
    setAttribute(Qt::WA_DeleteOnClose, true);

    QPushButton *pbSubscribe = new QPushButton();
    pbSubscribe->setText(tr("subscribe"));
    connect(pbSubscribe, &QPushButton::clicked, this, [=](){
//        qDebug() << "subscribe";
        Application::getInstance()->subscribe(EV_Test, moduleManager);
        Application::getInstance()->subscribe(EV_Test, this);
    });

    QPushButton *pbUnsubscribe = new QPushButton();
    pbUnsubscribe->setText(tr("unsubscribe"));
    connect(pbUnsubscribe, &QPushButton::clicked, this, [=](){
//        qDebug() << "unsubscribe";
        Application::getInstance()->unsubscribe(EV_Test, moduleManager);
    });

    QPushButton *pbPublish = new QPushButton();
    pbPublish->setText(tr("publish"));
    connect(pbPublish, &QPushButton::clicked, this, [=](){
//        qDebug() << "publish";

//        QEvent *ev = new CustomEvent((QEvent::Type)EV_Test);
//        Application::getInstance()->publish(ev);
//        delete ev;

        CustomEvent ev = CustomEvent((QEvent::Type)EV_Test);
        Application::getInstance()->publish(&ev);
    });

    QHBoxLayout *hbl = new QHBoxLayout();
    hbl->addWidget(pbSubscribe);
    hbl->addWidget(pbUnsubscribe);
    hbl->addWidget(pbPublish);
    setLayout(hbl);
}

void TestPage::customEvent(QEvent *event)
{
    quint16 id = event->type();
    switch (id)
    {
        case EV_Test:
            qDebug() << "TestPage EV_Test";
        break;
        default:
        break;
    }
}

void TestPage::closeEvent(QCloseEvent *event)
{
    Application::getInstance()->unsubscribe(EV_Test, this);
    event->accept();
}
